package client;

import java.util.ArrayList;
import java.util.Observable;

public class MirrorLocalOnRemoteTask extends Observable implements Runnable {

	private SyncClient client = null;

	private ArrayList<String[]> filesToPut = null, filesToDelete = null;

	public MirrorLocalOnRemoteTask( SyncClient client, ArrayList<String[]> filesToPut, ArrayList<String[]> filesToDelete ) {
		this.client = client;
		this.filesToDelete = filesToDelete;
		this.filesToPut = filesToPut;
	}
	
	@Override
	public void run() {
		Integer completedTaskCount = 0;

		if( filesToDelete != null ) {
			for (String[] strings : filesToDelete) {
				String deleteResult = client.deleteRemoteFile( strings[0] );
				setChanged();
				notifyObservers(deleteResult);

				completedTaskCount++;
				setChanged();
				notifyObservers( completedTaskCount );

				try{
					Thread.sleep(10);
				}catch(InterruptedException ie){
					return;
				}
			}
		}

		if( filesToPut != null ) {
			while( filesToPut.size() > 0 ) {
				String[] currentFile = filesToPut.get( filesToPut.size() - 1 );
				filesToPut.remove( filesToPut.size() - 1 );

				String status = "Uploading file '"+currentFile[0]+"'.";
				setChanged();
				notifyObservers(status);

				String uploadResult = client.uploadFile( currentFile[0] );

				setChanged();
				notifyObservers(uploadResult);

				completedTaskCount++;
				setChanged();
				notifyObservers( completedTaskCount );

				try{
					Thread.sleep(10);
				}catch(InterruptedException ie){
					return;
				}
			}
		}

		String finishedMessage = "SYNC_FINISHED";
		setChanged();
		notifyObservers( finishedMessage );
	}

}
